<?php
class Admin_Groups  extends Admin_Controller{
	private $namespace = 'groups';
	function __construct(){
		parent::__construct();
		$this->load->model('groups_m');
		$this->check_permissions();
	}
	
	public function index(){
		$model = $this->groups_m->get_all();
		
		$this->template
			->set('model',$model)
			->set('action',$this->action)
			->build($this->controller.'/'.$this->method);
	}
	
	public function create(){
		
		$model = $this->input->post();
		$this->form_validation->set_rules('name', 'lang:users:groups:name', 'required|max_length[20]|is_unique[ser_groups.name]|trim|alpha_dash');
		
		$type =  substr($this->input->post('btnAction'), 0);
		
		if ( type_post($type) ) {
			if ($this->form_validation->run() == TRUE)
			{
				$skip = array('btnAction','id');
				foreach($skip as $obj){
				if(array_key_exists($obj,$model)){
					unset($model[$obj]); 
					}
				}
				$id_insert = $this->groups_m->insert($model);
				$this->redirect_to_action($this->method,$this->namespace,$type,$id_insert);
			}
			
		}
//		echo lang('users:groups:group');exit;
		$this->template
			//->title(lang('users:groups:group'))
			->set_breadcrumb(lang('users:groups:group'));
		$this->view(array('model'=>$model));
	}
	public function edit($id){
		
		$model = (array)$this->groups_m->get($id);
		
		$is_unique =  '';
		if($this->input->post('name') != $model['name']) {
		   $is_unique =  '|is_unique[ser_groups.name]';
		}
		
		$this->form_validation->set_rules('name', 'lang:users:groups:name', 'required|max_length[20]|trim|alpha_dash|'.$is_unique);
		
		$type =  substr($this->input->post('btnAction'), 0);
		
		if ( type_post($type) ) {
			if ($this->form_validation->run() == TRUE)
			{
				$model =  $this->input->post();
				$skip = array('btnAction','id');
				foreach($skip as $obj){
				if(array_key_exists($obj,$model)){
					unset($model[$obj]); 
					}
				}
				$this->groups_m->update($id,$model);
				$this->redirect_to_action($this->method,$this->namespace,$type,$id);
			}
			
		}
		$this->view(array('model'=>$model));
	}
	
	public function delete($id){
		if($id == $this->current_user->group_id){
			$this->session->set_flashdata('error', lang('users:delete:group_current'));
		}
		elseif($id != 1 && $id != 2 && $id != 3)
			$this->groups_m->delete($id);
			else
				$this->session->set_flashdata('error', lang('users:delete:error'));
		redirect('admin/users/groups');
	}
	
	
}